#include "server.h"
#include <QHostAddress>


////////////////////////////////////////////
/// 辅助函数
////////////////////////////////////////////

zzy_mims::UserInfo getTestPBUserInfo(int i,const QByteArray& avatar)
{
    zzy_mims::UserInfo userInfo;
    QString variabel = QString::number(i);
    userInfo.setUserId(variabel);
    userInfo.setNickname("服务器提供的测试假名"+variabel);
    userInfo.setDescription("服务器提供的测试签名"+variabel);
    userInfo.setPhone("17373124944");
    userInfo.setAvatar(avatar);
    return userInfo;
}
//生成一个消息是文本类型的测试消息信息
zzy_mims::MessageInfo getPBTextMessageInfo(int i,const QByteArray& avatar)
{
    zzy_mims::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(i));
    messageInfo.setChatSessionId(QString::number(i));
    messageInfo.setSender(getTestPBUserInfo(i,avatar));
    messageInfo.setTimestamp(model::getCurrentTime());
    zzy_mims::MessageContent cont;
    zzy_mims::StringMessageInfo sMessageInfo;
    sMessageInfo.setContent("测试消息"+QString::number(i));
    cont.setStringMessage(sMessageInfo);
    cont.setMessageType(zzy_mims::MessageTypeGadget::STRING);
    messageInfo.setMessage(cont);
    return messageInfo;
}

//生成一个消息是图片类型的测试消息信息
zzy_mims::MessageInfo getPBImageMessageInfo(int i,const QByteArray& avatar)
{
    zzy_mims::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(i));
    messageInfo.setChatSessionId(QString::number(i));
    messageInfo.setSender(getTestPBUserInfo(i,avatar));
    messageInfo.setTimestamp(model::getCurrentTime());
    zzy_mims::MessageContent cont;
    zzy_mims::ImageMessageInfo iMessageInfo;
    iMessageInfo.setFileId("testImage");
    //需要内容时，让客户端从服务器再发送申请
    iMessageInfo.setImageContent("");
    cont.setImageMessage(iMessageInfo);
    cont.setMessageType(zzy_mims::MessageTypeGadget::IMAGE);
    messageInfo.setMessage(cont);
    return messageInfo;
}
//生成一个消息是文件类型的测试消息信息
zzy_mims::MessageInfo getPBFileMessageInfo(int i,const QByteArray& avatar)
{
    zzy_mims::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(i));
    messageInfo.setChatSessionId(QString::number(i));
    messageInfo.setSender(getTestPBUserInfo(i,avatar));
    messageInfo.setTimestamp(model::getCurrentTime());
    zzy_mims::MessageContent cont;
    zzy_mims::FileMessageInfo fMessageInfo;
    fMessageInfo.setFileId("testFile");
    fMessageInfo.setFileName("test.txt");    //这里先设置为0
    fMessageInfo.setFileSize(0);
    fMessageInfo.setFileContents("");
    cont.setFileMessage(fMessageInfo);
    cont.setMessageType(zzy_mims::MessageTypeGadget::FILE);
    messageInfo.setMessage(cont);
    return messageInfo;
}
//生成一个消息是语音类型的测试消息信息
zzy_mims::MessageInfo getPBSpeechMessageInfo(int i,const QByteArray& avatar)
{
    zzy_mims::MessageInfo messageInfo;
    messageInfo.setMessageId(QString::number(i));
    messageInfo.setChatSessionId(QString::number(i));
    messageInfo.setSender(getTestPBUserInfo(i,avatar));
    messageInfo.setTimestamp(model::getCurrentTime());
    zzy_mims::MessageContent cont;
    zzy_mims::SpeechMessageInfo spMessageInfo;
    spMessageInfo.setFileContents("");
    spMessageInfo.setFileId("testSpeech");
    cont.setSpeechMessage(spMessageInfo);
    cont.setMessageType(zzy_mims::MessageTypeGadget::SPEECH);
    messageInfo.setMessage(cont);
    return messageInfo;
}
//生成一个会话的最后一条消息是文本类型的测试会话信息
zzy_mims::ChatSessionInfo getPBTextSessionInfo(int i,const QByteArray& avatar,bool isGroup)
{
    zzy_mims::ChatSessionInfo sessionInfo;
    sessionInfo.setChatSessionId(QString::number(i));
    if(isGroup)
    {
        sessionInfo.setChatSessionName("群聊"+QString::number(i));
        sessionInfo.setSingleChatFriendId("");
    }
    else
    {
        sessionInfo.setChatSessionName("会话"+QString::number(i));
        sessionInfo.setSingleChatFriendId(QString::number(i));
    }
    sessionInfo.setAvatar(avatar);
    zzy_mims::MessageInfo prevMessageInfo = getPBTextMessageInfo(i,avatar);
    sessionInfo.setPrevMessage(prevMessageInfo);
    return sessionInfo;
}


HttpServer* HttpServer::instance = nullptr;

HttpServer* HttpServer::getInstance()
{
    if(!instance)
        instance = new HttpServer;
    return instance;
}

bool HttpServer::init()
{
    //listen函数返回值是成功绑定的端口号
    int ret = httpServer.listen(QHostAddress::Any,8000);

    // //设置路由
    httpServer.route("/ping",[](const QHttpServerRequest& req)
    {
        (void)req;
        LOG()<<"[http] 收到ping请求";
        return "pong";
    });
    httpServer.route("/service/user/get_user_info",[=](const QHttpServerRequest &req){return getUserInfo(req);});
    httpServer.route("/service/friend/get_friend_list",[=](const QHttpServerRequest &req){return getFriendList(req);});
    httpServer.route("/service/friend/get_chat_session_list",[=](const QHttpServerRequest &req){return getSessionList(req);});
    httpServer.route("/service/friend/get_pending_friend_events",[=](const QHttpServerRequest &req){return getApplyList(req);});
    httpServer.route("/service/message_storage/get_recent",[=](const QHttpServerRequest &req){return getRecentMessageList(req);});
    httpServer.route("/service/message_transmit/new_message",[=](const QHttpServerRequest &req){return newMessage(req);});
    httpServer.route("/service/user/set_nickname",[=](const QHttpServerRequest &req){return setNickname(req);});
    httpServer.route("/service/user/set_description",[=](const QHttpServerRequest &req){return setDesc(req);});
    httpServer.route("/service/user/get_phone_verify_code",[=](const QHttpServerRequest &req){return getVertifyCode(req);});
    httpServer.route("/service/user/set_phone",[=](const QHttpServerRequest &req){return setPhone(req);});
    httpServer.route("/service/user/set_avatar",[=](const QHttpServerRequest &req){return setAvatar(req);});
    httpServer.route("/service/friend/remove_friend",[=](const QHttpServerRequest &req){return deleteFriend(req);});
    httpServer.route("/service/friend/add_friend_apply",[=](const QHttpServerRequest &req){return sendApply(req);});
    httpServer.route("/service/friend/add_friend_process",[=](const QHttpServerRequest &req){return processsApply(req);});
    httpServer.route("/service/friend/search_friend",[=](const QHttpServerRequest &req){return searchUser(req);});
    httpServer.route("/service/friend/create_chat_session",[=](const QHttpServerRequest &req){return createSession(req);});
    httpServer.route("/service/friend/get_chat_session_member",[=](const QHttpServerRequest &req){return getSessionMemberList(req);});
    httpServer.route("/service/message_storage/search_history",[=](const QHttpServerRequest &req){return searchMessage(req);});
    httpServer.route("/service/message_storage/get_history",[=](const QHttpServerRequest &req){return searchMessageByTime(req);});
    httpServer.route("/service/user/username_login",[=](const QHttpServerRequest &req){return userLogin(req);});
    httpServer.route("/service/user/username_register",[=](const QHttpServerRequest &req){return userRegister(req);});
    httpServer.route("/service/user/phone_login",[=](const QHttpServerRequest &req){return phoneLogin(req);});
    httpServer.route("/service/user/phone_register",[=](const QHttpServerRequest &req){return phoneRegister(req);});
    httpServer.route("/service/file/get_single_file",[=](const QHttpServerRequest &req){return getSingleFile(req);});

    return ret==8000;
}

QHttpServerResponse HttpServer::getUserInfo(const QHttpServerRequest &req)
{
    //解析请求,把req的body取出来，并且通过pb进行反序列化
    zzy_mims::GetUserInfoReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取用户信息] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId();
    //构造响应数据
    zzy_mims::GetUserInfoRsp pbRsp;
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setErrmsg("");
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/myAvatar.jpg");
    pbRsp.setUserInfo(getTestPBUserInfo(1,avatar));

    QByteArray body = pbRsp.serialize(&serializer);

    //构造HTTP响应数据
    QHttpServerResponse httpRsp(body,QHttpServerResponse::StatusCode::Ok);
    httpRsp.setHeader("Content-Type","application/x-protobuf");
    return httpRsp;
}

QHttpServerResponse HttpServer::getFriendList(const QHttpServerRequest &req)
{
    //解析请求,把req的body取出来，并且通过pb进行反序列化
    zzy_mims::GetFriendListReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取好友列表] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId();

    //构造响应数据
    zzy_mims::GetFriendListRsp pbRsp;
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setErrmsg("");
    //这个设计从磁盘读文件的IO操作，耗时较长，不能放进循环
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    for(int i =1;i<=15;i++)
    {
        zzy_mims::UserInfo userInfo = getTestPBUserInfo(i,avatar);
        pbRsp.friendList().push_back(userInfo);
    }
    QByteArray body = pbRsp.serialize(&serializer);

    //构造HTTP响应数据
    QHttpServerResponse httpRsp(body,QHttpServerResponse::StatusCode::Ok);
    httpRsp.setHeader("Content-Type","application/x-protobuf");
    return httpRsp;
}

QHttpServerResponse HttpServer::getSessionList(const QHttpServerRequest &req)
{
    //解析请求,把req的body取出来，并且通过pb进行反序列化
    zzy_mims::GetChatSessionListReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取会话列表] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId();

    //构造响应数据
    zzy_mims::GetChatSessionListRsp pbRsp;
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setErrmsg("");
    //这个设计从磁盘读文件的IO操作，耗时较长，不能放进循环
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    //构造若干个单聊会话
    for(int i =1;i<=5;i++)
    {
        zzy_mims::ChatSessionInfo sessionInfo = getPBTextSessionInfo(i,avatar,0);
        pbRsp.chatSessionInfoList().push_back(sessionInfo);
    }
    //构造群聊会话
    const QByteArray groupAvatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    zzy_mims::ChatSessionInfo sessionInfo = getPBTextSessionInfo(6,groupAvatar,1);
    pbRsp.chatSessionInfoList().push_back(sessionInfo);
    QByteArray body = pbRsp.serialize(&serializer);

    //构造HTTP响应数据
    QHttpServerResponse httpRsp(body,QHttpServerResponse::StatusCode::Ok);
    httpRsp.setHeader("Content-Type","application/x-protobuf");
    return httpRsp;
}
QHttpServerResponse HttpServer::getApplyList(const QHttpServerRequest &req)
{
    zzy_mims::GetPendingFriendEventListReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取好友申请列表] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId();

    zzy_mims::GetPendingFriendEventListRsp pbRsp;
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setErrmsg("");
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    for(int i =0;i<10;i++)
    {
        zzy_mims::FriendEvent event;
        zzy_mims::UserInfo userInfo = getTestPBUserInfo(i,avatar);
        event.setEventId("");//不使用，设为空
        event.setSender(userInfo);
        pbRsp.event().push_back(event);
    }
    QByteArray body = pbRsp.serialize(&serializer);
    QHttpServerResponse httpRsp(body,QHttpServerResponse::StatusCode::Ok);
    return httpRsp;
}
QHttpServerResponse HttpServer::getRecentMessageList(const QHttpServerRequest &req)
{
    zzy_mims::GetRecentMsgReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取最近消息列表] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId();

    zzy_mims::GetRecentMsgRsp pbRsp;
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setErrmsg("");
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    int i =0;
    for(;i<20;i++)
    {
        zzy_mims::MessageInfo messageInfo = getPBTextMessageInfo(i,avatar);
        pbRsp.msgList().push_back(messageInfo);
    }
    for(;i<30;i++)
    {
        zzy_mims::MessageInfo messageInfo = getPBImageMessageInfo(i,avatar);
        pbRsp.msgList().push_back(messageInfo);
    }
    for(;i<40;i++)
    {
        zzy_mims::MessageInfo messageInfo = getPBFileMessageInfo(i,avatar);
        pbRsp.msgList().push_back(messageInfo);
    }
    for(;i<50;i++)
    {
        zzy_mims::MessageInfo messageInfo = getPBSpeechMessageInfo(i,avatar);
        pbRsp.msgList().push_back(messageInfo);
    }
    QByteArray body = pbRsp.serialize(&serializer);
    QHttpServerResponse httpRsp(body,QHttpServerResponse::StatusCode::Ok);
    return httpRsp;
}

QHttpServerResponse HttpServer::newMessage(const QHttpServerRequest &req)
{
    zzy_mims::NewMessageReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取最近消息列表] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId()
          <<",chatSessionId="<<pbReq.chatSessionId()<<",messageType="<<pbReq.message().messageType();
    if(pbReq.message().messageType()==zzy_mims::MessageTypeGadget::MessageType::STRING)
        LOG()<<"发送的文本消息为:"<<pbReq.message().stringMessage().content();
    zzy_mims::NewMessageRsp pbRsp;
    pbRsp.setSuccess(true);
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    QByteArray body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setNickname(const QHttpServerRequest &req)
{
    zzy_mims::SetUserNicknameReq pbReq;
    pbReq.deserialize(&serializer,req.body());

    LOG()<<"[REQ 修改姓名] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId()
          <<",newNickname="<<pbReq.nickname();
    zzy_mims::SetUserNicknameRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setSuccess(true);
    pbRsp.setRequestId(pbReq.requestId());

    const QByteArray body =pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setDesc(const QHttpServerRequest &req)
{
    zzy_mims::SetUserDescriptionReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 修改签名] requestId="<<pbReq.requestId()<<", loginSessionId="<<pbReq.sessionId()
          <<",newDesc="<<pbReq.description();
    zzy_mims::SetUserDescriptionRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getVertifyCode(const QHttpServerRequest &req)
{
    zzy_mims::PhoneVerifyCodeReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取验证码] requestId="<<pbReq.requestId()<<", phone:"<<pbReq.phoneNumber();
    zzy_mims::PhoneVerifyCodeRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setVerifyCodeId("testVertifyCodeId");
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setPhone(const QHttpServerRequest &req)
{
    zzy_mims::SetUserPhoneNumberReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 修改手机号] requestId="<<pbReq.requestId()<<", newPhone:"<<pbReq.phoneNumber();
    zzy_mims::SetUserPhoneNumberRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::setAvatar(const QHttpServerRequest &req)
{
    zzy_mims::SetUserAvatarReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 修改头像号] requestId="<<pbReq.requestId();
    zzy_mims::SetUserAvatarRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::deleteFriend(const QHttpServerRequest &req)
{
    zzy_mims::FriendRemoveReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 删除好友] requestId="<<pbReq.requestId()
          <<",操作者:"<<pbReq.userId()<<",被删除的人:"<<pbReq.peerId();
    zzy_mims::FriendRemoveRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::sendApply(const QHttpServerRequest &req)
{
    zzy_mims::FriendAddReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 发送好友申请] requestId="<<pbReq.requestId()
          <<",发送者:"<<pbReq.userId()<<",接受者:"<<pbReq.respondentId();
    zzy_mims::FriendAddRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::processsApply(const QHttpServerRequest &req)
{
    zzy_mims::FriendAddProcessReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 处理好友申请] requestId="<<pbReq.requestId()
          <<",发送者:"<<pbReq.applyUserId()<<",接受者:"<<pbReq.userId();
    zzy_mims::FriendAddProcessRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setNewSessionId("");
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::searchUser(const QHttpServerRequest &req)
{
    zzy_mims::FriendSearchReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 搜索用户] requestId="<<pbReq.requestId()
          <<",用户:"<<pbReq.userId()<<",key:"<<pbReq.searchKey();
    zzy_mims::FriendSearchRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    //构造若干个单聊会话
    for(int i =1;i<=5;i++)
    {
        zzy_mims::UserInfo userInfo = getTestPBUserInfo(i,avatar);
        pbRsp.userInfo().push_back(userInfo);
    }

    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::createSession(const QHttpServerRequest &req)
{
    zzy_mims::ChatSessionCreateReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 创建群聊] requestId="<<pbReq.requestId()
          <<",用户:"<<pbReq.userId()<<",成员列表:"<<pbReq.memberIdList();
    zzy_mims::ChatSessionCreateRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    zzy_mims::ChatSessionInfo sessionInfo = getPBTextSessionInfo(100,avatar,true);
    sessionInfo.setChatSessionName(pbReq.chatSessionName());
    pbRsp.setChatSessionInfo(sessionInfo);

    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getSessionMemberList(const QHttpServerRequest &req)
{
    zzy_mims::GetChatSessionMemberReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 创建群聊] requestId="<<pbReq.requestId()
          <<",用户:"<<pbReq.userId()<<",sessionId:"<<pbReq.sessionId();
    zzy_mims::GetChatSessionMemberRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    for(int i =0;i<12;i++)
    pbRsp.memberInfoList().push_back(getTestPBUserInfo(100+i,avatar));

    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::searchMessage(const QHttpServerRequest &req)
{
    zzy_mims::MsgSearchReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 搜索历史消息] requestId="<<pbReq.requestId()
          <<",用户:"<<pbReq.userId()<<",sessionId:"<<pbReq.sessionId();
    zzy_mims::MsgSearchRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    int i =0;
    for(;i<19;i++)
        pbRsp.msgList().push_back(getPBTextMessageInfo(100+i,avatar));
    for(;i<24;i++)
        pbRsp.msgList().push_back(getPBImageMessageInfo(100+i,avatar));
    for(;i<29;i++)
        pbRsp.msgList().push_back(getPBFileMessageInfo(100+i,avatar));
    for(;i<34;i++)
        pbRsp.msgList().push_back(getPBSpeechMessageInfo(100+i,avatar));

    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::searchMessageByTime(const QHttpServerRequest &req)
{
    zzy_mims::GetHistoryMsgReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 搜索历史消息] requestId="<<pbReq.requestId()
          <<",用户:"<<pbReq.userId()<<",sessionId:"<<pbReq.sessionId()<<"初始时间:"
          <<model::toFormatTime(pbReq.startTime())<<"结束时间:"<<model::toFormatTime(pbReq.overTime());
    zzy_mims::GetHistoryMsgRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
    int i =0;
    for(;i<16;i++)
        pbRsp.msgList().push_back(getPBTextMessageInfo(100+i,avatar));
    for(;i<21;i++)
        pbRsp.msgList().push_back(getPBImageMessageInfo(100+i,avatar));
    for(;i<26;i++)
        pbRsp.msgList().push_back(getPBFileMessageInfo(100+i,avatar));
    for(;i<31;i++)
        pbRsp.msgList().push_back(getPBSpeechMessageInfo(100+i,avatar));


    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::userLogin(const QHttpServerRequest &req)
{
    zzy_mims::UserLoginReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 用户登录] requestId="<<pbReq.requestId()<<"用户:"
          <<pbReq.nickname()<<"密码:"<<pbReq.password();

    zzy_mims::UserLoginRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setLoginSessionId("testLoginSessionId");

    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::userRegister(const QHttpServerRequest &req)
{
    zzy_mims::UserRegisterReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 用户注册] requestId="<<pbReq.requestId()<<"用户:"
          <<pbReq.nickname()<<"密码:"<<pbReq.password();

    zzy_mims::UserRegisterRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::phoneLogin(const QHttpServerRequest &req)
{
    zzy_mims::PhoneLoginReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 手机号登录] requestId="<<pbReq.requestId()<<"手机号:"
          <<pbReq.phoneNumber()<<"验证码:"<<pbReq.verifyCode();

    zzy_mims::PhoneLoginRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);
    pbRsp.setLoginSessionId("testPhoneLoginSessionId");

    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::phoneRegister(const QHttpServerRequest &req)
{
    zzy_mims::PhoneRegisterReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 手机号注册] requestId="<<pbReq.requestId()<<"手机号:"
          <<pbReq.phoneNumber()<<"验证码:"<<pbReq.verifyCode();

    zzy_mims::PhoneRegisterRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);

    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}

QHttpServerResponse HttpServer::getSingleFile(const QHttpServerRequest &req)
{
    zzy_mims::GetSingleFileReq pbReq;
    pbReq.deserialize(&serializer,req.body());
    LOG()<<"[REQ 获取单个文件] requestId="<<pbReq.requestId()<<"userId:"
          <<pbReq.userId()<<"fileId:"<<pbReq.fileId();

    zzy_mims::GetSingleFileRsp pbRsp;
    pbRsp.setErrmsg("");
    pbRsp.setRequestId(pbReq.requestId());
    pbRsp.setSuccess(true);


    zzy_mims::FileDownloadData fileDownloadData;
    if(pbReq.fileId()=="testImage")
        fileDownloadData.setFileContent(model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg"));
    else if(pbReq.fileId()=="testFile")
        fileDownloadData.setFileContent(model::loadFileToByteArray(":/myResource/file/test.txt"));
    else if(pbReq.fileId()=="testSpeech")
        fileDownloadData.setFileContent(model::loadFileToByteArray(":/myResource/file/tmpPlay.pcm"));
    else
    {
        pbRsp.setSuccess(false);
        pbRsp.setErrmsg("fileId异常");
    }
    pbRsp.setFileData(fileDownloadData);


    const QByteArray& body = pbRsp.serialize(&serializer);
    QHttpServerResponse rsp(body,QHttpServerResponse::StatusCode::Ok);
    rsp.setHeader("Content-Type","application/x-protobuf");
    return rsp;
}
WebSocketServer* WebSocketServer::instance = nullptr;
WebSocketServer* WebSocketServer::getInstance()
{
    if(!instance)
        instance = new WebSocketServer;
    return instance;
}

bool WebSocketServer::init()
{
    // 设置信号和槽
    connect(&webSocketServer,&QWebSocketServer::newConnection,this,[=]()
    {
        LOG()<<"[websocket] 连接建立成功";

        //获取到用来通信的socket对象
        QWebSocket* socket = webSocketServer.nextPendingConnection();
        LOG()<<"socket:"<<(long long)socket;
        connect(socket,&QWebSocket::disconnected,this,[=]()
        {
            LOG()<<"[websocket] 连接断开";
            disconnect(this,&WebSocketServer::sendTextNotify,this,nullptr);
            disconnect(this,&WebSocketServer::sendImageNotify,this,nullptr);
            disconnect(this,&WebSocketServer::sendFileNotify,this,nullptr);
            disconnect(this,&WebSocketServer::sendFriendAddApplyNotify,this,nullptr);
            disconnect(this,&WebSocketServer::sendSpeechNotify,this,nullptr);

        });

        connect(socket,&QWebSocket::errorOccurred,this,[=](QAbstractSocket::SocketError error)
        {
            LOG()<<"websocket连接出错"<<error;
        });
        connect(socket,&QWebSocket::textMessageReceived,this,[=](const QString& message)
        {
            LOG()<<"websocket收到文本消息"<<message;
        });
        connect(socket,&QWebSocket::binaryMessageReceived,this,[=](const QByteArray& byteArray)
        {
            LOG()<<"websocket收到二进制消息"<<byteArray.length();
        });
        connect(this,&WebSocketServer::sendTextNotify,this,[=]()
        {
            if(socket==nullptr||!socket->isValid())
            {
                LOG()<<"socket对象无效";
                return;
            }
            QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
            zzy_mims::MessageInfo msgInfo = getPBTextMessageInfo(3,avatar);
            zzy_mims::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(msgInfo);

            zzy_mims::NotifyMessage notifyMessage;
            notifyMessage.setNotifyType(zzy_mims::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);
            notifyMessage.setNotifyEventId("");

            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG()<<"发送文本消息:"<<msgInfo.message().stringMessage().content();
        });
        connect(this,&WebSocketServer::sendImageNotify,this,[=]()
        {
            if(socket==nullptr||!socket->isValid())
            {
                LOG()<<"socket对象无效";
                return;
            }
            QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
            zzy_mims::MessageInfo msgInfo = getPBImageMessageInfo(3,avatar);
            zzy_mims::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(msgInfo);

            zzy_mims::NotifyMessage notifyMessage;
            notifyMessage.setNotifyType(zzy_mims::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);
            notifyMessage.setNotifyEventId("");

            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG()<<"发送图片消息";
        });
        connect(this,&WebSocketServer::sendFileNotify,this,[=]()
        {
            if(socket==nullptr||!socket->isValid())
            {
                LOG()<<"socket对象无效";
                return;
            }
            QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
            zzy_mims::MessageInfo msgInfo = getPBFileMessageInfo(3,avatar);
            zzy_mims::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(msgInfo);

            zzy_mims::NotifyMessage notifyMessage;
            notifyMessage.setNotifyType(zzy_mims::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);
            notifyMessage.setNotifyEventId("");

            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG()<<"发送文件消息";
        });
        connect(this,&WebSocketServer::sendSpeechNotify,this,[=]()
        {
            if(socket==nullptr||!socket->isValid())
            {
                LOG()<<"socket对象无效";
                return;
            }
            QByteArray avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
            zzy_mims::MessageInfo msgInfo = getPBSpeechMessageInfo(3,avatar);
            zzy_mims::NotifyNewMessage notifyNewMessage;
            notifyNewMessage.setMessageInfo(msgInfo);

            zzy_mims::NotifyMessage notifyMessage;
            notifyMessage.setNotifyType(zzy_mims::NotifyTypeGadget::NotifyType::CHAT_MESSAGE_NOTIFY);
            notifyMessage.setNewMessageInfo(notifyNewMessage);
            notifyMessage.setNotifyEventId("");

            QByteArray body = notifyMessage.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG()<<"发送语音消息";
        });

        connect(this,&WebSocketServer::sendFriendAddApplyNotify,this,[=]()
        {
            if(socket==nullptr||!socket->isValid())
            {
                LOG()<<"socket对象无效";
                return;
            }
            zzy_mims::NotifyMessage notify;
            zzy_mims::NotifyFriendAddApply notifyFriendAddApply;
            const QByteArray& avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
            notifyFriendAddApply.setUserInfo(getTestPBUserInfo(18,avatar));

            notify.setNotifyType(zzy_mims::NotifyTypeGadget::NotifyType::FRIEND_ADD_APPLY_NOTIFY);
            notify.setFriendAddApply(notifyFriendAddApply);
            notify.setNotifyEventId("");

            const QByteArray& body = notify.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG()<<"18号成员向1号客户端发送好友申请";
        });
        connect(this,&WebSocketServer::sendFriendAddApplyProcessNotify,this,[=](bool isAgree)
        {
            if(socket==nullptr||!socket->isValid())
            {
                LOG()<<"socket对象无效";
                return;
            }
            zzy_mims::NotifyMessage notify;
            zzy_mims::NotifyFriendAddProcess notifyFriendAddProcess;
            const QByteArray& avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");
            notifyFriendAddProcess.setUserInfo(getTestPBUserInfo(18,avatar));
            notifyFriendAddProcess.setAgree(isAgree);

            notify.setNotifyType(zzy_mims::NotifyTypeGadget::FRIEND_ADD_PROCESS_NOTIFY);
            notify.setFriendProcessResult(notifyFriendAddProcess);
            notify.setNotifyEventId("");

            const QByteArray& body = notify.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG()<<"18号成员处理了1号客户端发送的好友申请";
        });
        connect(this,&WebSocketServer::sendCreateSessionNotify,this,[=](bool isAgree)
        {
            if(socket==nullptr||!socket->isValid())
            {
                LOG()<<"socket对象无效";
                return;
            }
            zzy_mims::NotifyMessage notify;
            zzy_mims::NotifyNewChatSession notifyNewChatSession;
            const QByteArray& avatar = model::loadFileToByteArray(":/myResource/Image/dogAvatar.svg");

            notifyNewChatSession.setChatSessionInfo(getPBTextSessionInfo(101,avatar,true));
            notify.setNotifyType(zzy_mims::NotifyTypeGadget::CHAT_SESSION_CREATE_NOTIFY);
            notify.setNewChatSessionInfo(notifyNewChatSession);
            notify.setNotifyEventId("");

            const QByteArray& body = notify.serialize(&serializer);
            socket->sendBinaryMessage(body);
            LOG()<<"创建出了101号群聊";
        });
    });
    bool ok = webSocketServer.listen(QHostAddress::Any,8001);
    return ok;
}
